package _17_函数式编程.Lambda._10_Lambda方法引用;

import _17_函数式编程.Lambda.Apple;
import org.junit.jupiter.api.Test;

import java.util.Arrays;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

public class _10_1_Lambda方法引用 {

    @Test
    public void listCompare(){
        List<String> list = Arrays.asList("a","b","A","B");

        //Lambda
        list.sort(
                (s1,s2) -> s1.compareToIgnoreCase(s2)
        );

        //方法引用
        list.sort(String::compareToIgnoreCase);

        printByConsumer(list, (String str) -> System.out.print(str + " "));
    }

    public static <T> void printByConsumer(List<T> list, Consumer<T> consumer){
        for (T t : list){
            consumer.accept(t);
        }
    }

    @Test
    public void stringToInt(){
        String str = "234";
        int num;

        //正常写法
        num = Integer.parseInt(str);
        System.out.println("正常写法：" + num);

        //Lambda
        Function<String,Integer> function = (String s) -> Integer.parseInt(s);
        System.out.println("Lambda写法：" + function.apply(str));

        //方法引用
        Function<String,Integer> function1 = Integer::parseInt;
        System.out.println("方法引用：" + function1.apply(str));
    }

    @Test
    public void newClass(){

        //正常写法
        Apple apple1 = new Apple("bule",123);
        System.out.println("苹果的颜色：" + apple1.getColor() + "，重量：" + apple1.getWeight());

        //Lambda写法
        Supplier<Apple> supplier = () -> new Apple("yellow",222);
        Apple apple2 = supplier.get();
        System.out.println("苹果的颜色：" + apple2.getColor() + "，重量：" + apple2.getWeight());

        //方法引用 —— 空构造函数
        Supplier<Apple> supplier1 = Apple::new;
        Apple apple3 = supplier1.get();
        System.out.println("苹果的颜色：" + apple3.getColor() + "，重量：" + apple3.getWeight());

        //方法引用 —— 非空构造函数
        BiFunction<String, Integer, Apple> biFunction = Apple::new;
        Apple apple4 = biFunction.apply("red",666);
        System.out.println("苹果的颜色：" + apple4.getColor() + "，重量：" + apple4.getWeight());
    }



}
